package com.moon.game.command.guest.market;

import com.moon.game.clazz.PlayerItemsProto.PlayerItems.PlayerItem;
import com.moon.game.command.BaseCmd;
import com.moon.game.command.RequestSession;
import com.moon.game.constants.Constants;
import com.moon.game.constants.ErrorCode;
import com.moon.game.exception.GException;
import com.moon.game.manager.ItemMG;
import com.moon.game.resource.model.Item;
import com.moon.game.service.PlayerItemService;
import com.moon.game.service.PlayerService;
import com.moon.game.vos.ErrorMsg;

/**
 * @description 出售装备类道具
 * @author Ranger 作者 E-mail:haozi000005@163.com
 * @version 创建时间：2012-6-16 下午8:31:11
 */
public class SellPlayerItemCmd extends BaseCmd{
	@Override
	protected void runOnce(RequestSession req) throws GException {
		switch (req.getStatus()) {
			case STATU_INIT:
				doInit(req);
				break;
			case STATU_CHECK:
				doCheckSelf(req);
				break;
			case STATU_RETURN:
				doResponse(req);
				break;
			default:
				break;
		}
	}

	@Override
	protected void doResponse(RequestSession req) throws GException {
		String[] ps = req.getClientRequest().getPs();
		if (ps == null) {
			doResponsePsError(req);
			return;
		}
		String playerId = req.getPlayerId();
		long playerItemId = Long.parseLong(ps[0]);
		req.setVO("player_item_id", playerItemId);
		PlayerItem playerItem = PlayerItemService.getPlayerItem(playerId, playerItemId);
		if (playerItem == null) {
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_HAVE_NO_THE_ITEM, "你要出售的装备已经不存在！"));
			return;
		}
		final Item item = ItemMG.instance.getItem(playerItem.getItemId());
		req.setVO("item_id", item.getId());
		int price = 100;
		if (item.getMoney() != null && item.getMoney().intValue() != 0) {
			int temp = (int) ((playerItem.getCurEndure() / item.getEndure())*(item.getMoney() / 1.5));
			if (temp != 0) {
				price = temp;
			}
		}
		if (ps.length == 1) {
			req.setVO("item_name", item.getName());
			req.setVO("price", price);
			doResult(req, "ack");
			return;
		}
		Integer ack = Integer.parseInt(ps[1]);
		if (ack == null || ack != 1) {
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_LACK_THE_ITEM, "参数错误,出售" + item.getName() + "失败！"));
			return;
		}
		StringBuffer info = new StringBuffer();
		int ret = PlayerItemService.delPlayerItem(playerId, playerItemId);
		if (ret == Constants.DEL_ITEM_SUCC) {
			info.append("出售 "+ item.getName() +"成功，您的碎银增加：+" + price);
			req.setVO(TAG_INFO, info);
			PlayerService.doAddMoney(req.getSid(), req.getPlayerId(), price);
		}else if (ret == Constants.DEL_ITEM_LACK) {
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_HAVE_NO_THE_ITEM, "你要出售的装备已经不存在！"));
			return;
		}
		response(req, req.getClientResponse());
	}

}
